package com.sx.pipeline.ui.provide.detail

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.lxj.xpopup.XPopup
import com.sx.mvvmlibs.base.EasyAdapter
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.ReleaseImageAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.CustomCommonPicket
import com.sx.pipeline.custom.dialog.DialogPasswordInput
import com.sx.pipeline.databinding.ActProvideDetailBinding
import com.sx.pipeline.ui.provide.ProvideVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CountDownUtil


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 供应列表
 */
@Route(path = RoutePath.Provide.PROVIDE_DETAIL)
class ProvideDetailActivity :
    CYDataBindingBaseActivity<ActProvideDetailBinding, ProvideVM>(R.layout.act_provide_detail),
    View.OnClickListener {
    @JvmField
    @Autowired(name = IntentKey.ID)
    var supplyId: Int? = 0

    private var payMoney="" //支付管币金额

    private var mImageAdapter: ReleaseImageAdapter? = null//附件图片适配器

    private var countDownUtil: CountDownUtil? = null //供应倒计时工具类

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        mViewModel.getSupply()
        //请求供应详情数据
        supplyId?.let { mViewModel.getSupplyOrderDetail(it) }
        //获取询价价格
        mViewModel.getInquiryPrice()
    }


    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.supplyDetailEvent) {
            //标题
            mBinding.tvName.text = it?.title
            //供应数量
            mBinding.tvDesc.text = "内容描述：" + it?.supplyDescribe
            //供应时间
            mBinding.tvProvideTime.text = "供应时间：" + it?.startTime + "-" + it?.endTime
            //供应服务区域
            mBinding.tvProvideArea.text = "供应服务区域：" + it?.addressDetail
            //供应负责人
            mBinding.tvProvidePrincipal.text = "供应负责人：" + it?.contact
            //发布时间
            mBinding.tvCreateTime.text = "发布时间：" + it?.createTime
            payMoney= it?.payMoney.toString()

            if (!TextUtils.isEmpty(it?.annexUrl)){
                it?.annexUrl?.split(",")?.let { it1 -> initDocutmentImg(it1) }
                mBinding.rvImg.visibility=View.VISIBLE
            }

            val endtime = AndroidUtil.date2TimeStamp(it?.endTime, "yyyy-MM-dd HH:mm")
            //初始化供应任务定时
            endtime?.toLong()?.let { it1 -> initTimer(it1) }

            //是否已经询价 已询价展示 询价设备信息和询价信息 / 添加询价
            if (it?.omsSupplyInquiry == null) {
                //显示添加询价
                mBinding.tabAddInquiry.visibility = View.VISIBLE
                mBinding.tvSubmit.text = getString(R.string.txt_add_inquiry_price)
                //负责人联系电话
                mBinding.tvProvideContact.text = "联系方式：**** **** ****"
            } else {
                //负责人联系电话
                mBinding.tvProvideContact.text = "联系方式：" + it?.contactPhone
                //显示 设备信息和我的询价信息
                //设备信息
                Glide.with(this).load(it.pmsServer.images).into(mBinding.ivDeviceImg)
                mBinding.tvDeviceName.text = it.pmsServer.title

                //询价信息
                mBinding.tvNeedNumber.text = "需要数量：" + it.omsSupplyInquiry.quantity
                mBinding.tvNeedTime.text =
                    "供货时间：" + it.omsSupplyInquiry.startTime + "-" + it.omsSupplyInquiry.endTime

                mBinding.tabDeviceInfo.visibility = View.VISIBLE
                mBinding.tabMyInquiry.visibility = View.VISIBLE
                mBinding.tvSubmit.text = getString(R.string.txt_dial_number)
            }
        }


        observe(mViewModel.providePriceEvent){
            if (it?.toInt()!=0){
                mBinding.tvProvideMoney.visibility=View.VISIBLE
                //价格
                mBinding.tvProvideMoney.text=it.toString()
            }

        }
    }

    private fun initTimer(endtime: Long) {
        if (countDownUtil == null) {
            countDownUtil = CountDownUtil()
        }
        Log.d("fsdf", "" + endtime)
        //倒计时
        countDownUtil!!.start((endtime!! * 1000), object :
            CountDownUtil.OnCountDownCallBack {
            @SuppressLint("SetTextI18n")
            override fun onProcess(
                day: String,
                hour: String,
                minute: String,
                second: String
            ) {
                mBinding.tvCountDown.text = day + "天" + hour + ":" + minute + ":" + second
            }

            override fun onFinish() {}
        })
    }

    //附件
    fun initDocutmentImg(data: List<String>) {
        mImageAdapter = ReleaseImageAdapter(this, data)
        mBinding.rvImg.layoutManager =
            GridLayoutManager(this, 3)
        mBinding.rvImg.adapter = mImageAdapter
        mImageAdapter?.selectMode = EasyAdapter.SelectMode.SINGLE_SELECT
    }


    override fun onResume() {
        super.onResume()
        //请求供应详情
        supplyId?.let { mViewModel.getSupplyOrderDetail(it) }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            //选择计量单位
            R.id.tv_measurement_unit -> {
//                if (mViewModel.supplyUnitData.size == 0) {
//                    ToastUtils.showShort("未获取到数据")
//                    return
//                }
//                val popup =
//                    CustomCommonPicket(this, getString(R.string.txt_choose_measurement_unit))
//                popup.setPickerData(mViewModel.supplyUnitData)
//                popup.setCommonPickerListener { _, data ->
//                    mBinding.tvMeasurementUnit.text = data
//                }
//                XPopup.Builder(this)
//                    .borderRadius(42f)
//                    .isDarkTheme(false)
//                    .asCustom(popup)
//                    .show()
            }
            R.id.tv_use_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择开始时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        mBinding.tvUseTime.text =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.tv_end_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择结束时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        mBinding.tvEndTime.text =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            //查看设备详情
            R.id.tab_device_info -> {
//                mViewModel.supplyDetailEvent.value?.equipmentId?.let {
//                    RouteManager.Mine.intentToDeviceDetail(
//                        it, true,false)
//                }
            }
            //添加询价
            R.id.tv_submit -> {
                if (mViewModel.supplyDetailEvent.value?.omsSupplyInquiry == null) {
                    if (TextUtils.isEmpty(mBinding.etContact.text.toString())){
                        ToastUtils.showShort("请填写联系人")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.etContactNum.text.toString())){
                        ToastUtils.showShort("请填写联系方式")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.etNum.text.toString())){
                        ToastUtils.showShort("请填写数量")
                        return
                    }
//                    if (TextUtils.isEmpty(mBinding.tvMeasurementUnit.text.toString())){
//                        ToastUtils.showShort("请填写计量单位")
//                        return
//                    }
                    if (TextUtils.isEmpty(mBinding.tvUseTime.text.toString())){
                        ToastUtils.showShort("请选择开始时间")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.tvEndTime.text.toString())){
                        ToastUtils.showShort("请选择结束时间")
                        return
                    }
                    if (mViewModel.providePriceEvent.value?.toInt()==0){
                        //添加询价
                        supplyId?.let {
                            mViewModel.addInquiry(
                                it,
                                mBinding.etContact.text.toString(),
                                mBinding.etContactNum.text.toString(),
                                mBinding.etNum.text.toString(),
                                mBinding.tvMeasurementUnit.text.toString(),
                                mBinding.tvUseTime.text.toString(),
                                mBinding.tvEndTime.text.toString(),
                                ""
                            )
                    }

                    }else{
                        val popup =
                            DialogPasswordInput(this, mViewModel.providePriceEvent.value.toString()).setPassInputListener { pass ->
                                //添加询价
                                supplyId?.let {
                                    mViewModel.addInquiry(
                                        it,
                                        mBinding.etContact.text.toString(),
                                        mBinding.etContactNum.text.toString(),
                                        mBinding.etNum.text.toString(),
                                        mBinding.tvMeasurementUnit.text.toString(),
                                        mBinding.tvUseTime.text.toString(),
                                        mBinding.tvEndTime.text.toString(),
                                        pass
                                    )
                                }
                            }
                        XPopup.Builder(this)
                            .borderRadius(42f)
                            .isDarkTheme(false)
                            .asCustom(popup)
                            .show()
                    }

                } else {
                    //拨打电话
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asConfirm(
                            getString(R.string.txt_please_confirm_mobile_number), mViewModel.supplyDetailEvent.value?.contactPhone+"该号码将被加密保护",
                            getString(R.string.cancel), getString(R.string.txt_dial_number),
                            {
                                mViewModel.supplyDetailEvent.value?.contactPhone?.let {
                                    AndroidUtil.toCallPhone(
                                        it,this)
                                }
                            }, null, false
                        ).show()
                }

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //销毁定时器
        countDownUtil?.onDestroy()
    }

}